<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="知识库名称" prop="name">
        <el-input
            v-model="queryParams.name"
            placeholder="请输入知识库名称"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['ai:aiKnowledge:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['ai:aiKnowledge:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['ai:aiKnowledge:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="aiKnowledgeList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="ID" align="center" prop="id"/>
      <el-table-column label="知识库名称" align="center" prop="name" show-overflow-tooltip/>
      <el-table-column label="向量数据库" show-overflow-tooltip>
        <template #default="scope">
          {{ getAiEmbeddingDbName(scope.row.embeddingDbId) }}
        </template>
      </el-table-column>
      <el-table-column label="向量模型名称" show-overflow-tooltip>
        <template #default="scope">
          {{ getRankModelName(scope.row.rankModelId) }}
        </template>
      </el-table-column>
      <el-table-column label="重排向量模型名称" show-overflow-tooltip>
        <template #default="scope">
          {{ getReRankModelName(scope.row.reRankModelId) }}
        </template>
      </el-table-column>
      <el-table-column label="分片规则器">
        <template #default="scope">
          <dict-tag :options="text_splitter_type" :value="scope.row.segmentType"/>
        </template>
      </el-table-column>
      <el-table-column label="分片最大字符数" align="center" prop="maxSegment"/>
      <el-table-column label="最大重叠字符数" align="center" prop="maxOverlap"/>
      <el-table-column label="向量数据库class" align="center" prop="vectorDb" show-overflow-tooltip/>
      <el-table-column label="备注" align="center" prop="remark" show-overflow-tooltip/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Document" @click="handleFiles(scope.row)" v-hasPermi="['ai:aiKnowledge:file']">文件</el-button>
          <el-button link type="primary" icon="MessageBox" @click="handleFp(scope.row)">召回</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['ai:aiKnowledge:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改知识库对话框 -->
    <el-dialog :title="title" v-model="open" width="800px" append-to-body destroy-on-close>
      <el-form ref="aiKnowledgeRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="知识库名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入知识库名称"/>
        </el-form-item>
        <el-form-item label="向量数据库" prop="embeddingDbId">
          <el-select v-model="form.embeddingDbId" placeholder="请选择向量模型名称">
            <el-option
                v-for="item in aiEmbeddingDbList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="向量模型名称" prop="rankModelId">
          <el-select v-model="form.rankModelId" placeholder="请选择向量模型名称">
            <el-option
                v-for="item in rankModelList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="重排模型名称" prop="reRankModelId">
          <el-select v-model="form.reRankModelId" placeholder="请选择重排模型名称">
            <el-option
                v-for="item in reRankModelList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="分片规则器" prop="segmentType">
          <el-select v-model="form.segmentType" placeholder="请选择分片规则器" @change="handleSelectSegmentTypeChange">
            <el-option
                v-for="item in text_splitter_type"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
          <div style="font-size: 12px;color: red">{{ textSplitterRemark }}</div>
        </el-form-item>
        <el-form-item label="分片最大字符" prop="maxSegment">
          <el-input-number :max="500" :min="1" v-model="form.maxSegment" style="width: 100%" placeholder="请输入分片最大字符数"/>
        </el-form-item>
        <el-form-item label="最大重叠字符" prop="maxOverlap">
          <el-input-number :max="500" :min="1" v-model="form.maxOverlap" style="width: 100%" placeholder="请输入最大重叠字符数"/>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-drawer title="知识库文档列表" v-model="filesOpen" size="85%" append-to-body destroy-on-close>
      <KnowledgeFile :aiKnowledgeId="form.id"/>
    </el-drawer>

    <!--分片按钮 对话框-->
    <el-dialog title="分片详情" v-model="detailFraOpen" width="80%" style="height: 90vh;"  append-to-body destroy-on-close>
      <el-row style="height: 75vh;overflow: auto">
        <el-col :span="14" style="height: 95%;overflow: auto">
          <el-card v-for="(item,index) in aiKnowledgeFragmentationList" style="margin-bottom: 15px;margin-right: 15px">
            <template #header>
              <div class="card-header">
                <span>分桶 - {{ item.id }}</span>
              </div>
            </template>

            <div style="font-size: 14px; color: #5a5e66">
              {{item.fragmentation}}
            </div>

          </el-card>
        </el-col>
        <el-col :span="1"/>
        <el-col :span="8">
          <el-card style="margin-bottom: 15px;">
            <template #header>
              <div class="card-header">
                <span>回归查询</span>
                <el-button type="primary" @click="handleQueryFragmentation" style="position: absolute;right: 5%;top: 5px;">查询</el-button>
              </div>
            </template>

            <el-input type="textarea" rows="3" v-model="queryText"></el-input>

            <el-divider />

            <p>查询结果：</p>
            <div style="max-height: 45vh;overflow: auto;padding: 5px 15px" v-html="queryTextResult">
            </div>
          </el-card>
        </el-col>
      </el-row>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancel">关 闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="AiKnowledge">
import {addAiKnowledge, delAiKnowledge, getAiKnowledge, listAiKnowledge, updateAiKnowledge} from "@/api/ai/aiKnowledge";
import {listAiEnableModel} from "@/api/ai/aiModel.js";
import KnowledgeFile from "@/views/ai/KnowledgeFile/index";
import {listAllByKnowledgeId, queryFragmentationBySearch} from "@/api/ai/aiKnowledgeFragmentation.js";
import {listAllAiEmbeddingDb} from "@/api/ai/aiEmbeddingDb.js";
import {getDicts} from "@/api/system/dict/data.js";

const {proxy} = getCurrentInstance();


const {text_splitter_type} = proxy.useDict("text_splitter_type");

const aiKnowledgeList = ref([]);
const open = ref(false);
const detailOpen = ref(false);
const detailFraOpen = ref(false);
const filesOpen = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const rankModelList = ref([]);
const reRankModelList = ref([]);
const aiKnowledgeFragmentationList = ref([]);
const queryText = ref(null)
const queryTextResult = ref(null)
const knowledgeId = ref(null)
const aiEmbeddingDbList = ref([]);
const textSplitterTypeDataList = ref([])
const textSplitterRemark = ref(null)

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: null,
    rankModelId: null,
    maxTokens: null,
    vectorDb: null,
  },
  rules: {
    name: [
      {required: true, message: "知识库名称不能为空", trigger: "blur"}
    ],
    embeddingDbId: [
      {required: true, message: "向量数据库不能为空", trigger: "blur"}
    ],
    rankModelId: [
      {required: true, message: "向量模型不能为空", trigger: "change"}
    ],
    reRankModelId: [
      {required: true, message: "重排序模型不能为空", trigger: "change"}
    ],
    segmentType: [
      {required: true, message: "分片规则器不能为空", trigger: "blur"}
    ],
    maxSegment: [
      {required: true, message: "分片最大字符数不能为空", trigger: "blur"}
    ],
    maxOverlap: [
      {required: true, message: "最大重叠字符数不能为空", trigger: "blur"}
    ],
  }
});

const {queryParams, form, rules} = toRefs(data);

/** 查询知识库列表 */
function getList() {
  loading.value = true;
  listAiKnowledge(queryParams.value).then(response => {
    aiKnowledgeList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

function getTextSplitterTypeDataList() {
  getDicts("text_splitter_type").then(response => {
    textSplitterTypeDataList.value = response.data
  })
}

function handleSelectSegmentTypeChange(obj) {
  const objData = textSplitterTypeDataList.value.find(item => item.dictValue === obj)
  textSplitterRemark.value = objData !== undefined ? objData.remark : ''
}

// 取消按钮
function cancel() {
  open.value = false;
  detailOpen.value = false;
  filesOpen.value = false;
  detailFraOpen.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    name: null,
    rankModelId: null,
    reRankModelId: null,
    maxTokens: null,
    vectorDb: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    remark: null
  };
  proxy.resetForm("aiKnowledgeRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  form.value.maxTokens = 500
  open.value = true;
  title.value = "添加知识库";
}

// 详情按钮操作
function handleDetail(row) {
  reset();
  const _id = row.id || ids.value
  getAiKnowledge(_id).then(response => {
    form.value = response.data;
    detailOpen.value = true;
    title.value = "知识库详情";
  });
}

function handleFp(row) {
  queryText.value = null
  reset();
  const _id = row.id || ids.value
  knowledgeId.value = _id
  listAllByKnowledgeId(_id).then(response => {
    aiKnowledgeFragmentationList.value = response.data;
    detailFraOpen.value = true;
  })
}

function handleQueryFragmentation() {
  queryFragmentationBySearch(knowledgeId.value, queryText.value).then(response => {
    queryTextResult.value = response.data
    queryTextResult.value = queryTextResult.value.replace(/\n/g, '<br />')
  })
}

function handleFiles(row) {
  form.value.id = row.id
  filesOpen.value = true;
}


/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getAiKnowledge(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改知识库";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["aiKnowledgeRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateAiKnowledge(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addAiKnowledge(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除知识库编号为"' + _ids + '"的数据项？').then(function () {
    return delAiKnowledge(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('ai/aiKnowledge/export', {
    ...queryParams.value
  }, `aiKnowledge_${new Date().getTime()}.xlsx`)
}


function getRankModelList() {
  const queryType = [4]
  listAiEnableModel(queryType).then(response => {
    rankModelList.value = response.data;
  });
}

function getReRankModelList() {
  const queryType = [5]
  listAiEnableModel(queryType).then(response => {
    reRankModelList.value = response.data;
  });
}

function getAiEmbeddingBb() {
  listAllAiEmbeddingDb().then(response => {
    aiEmbeddingDbList.value = response.data;
  })
}

function getAiEmbeddingDbName(mId) {
  const aiEmbeddingDb = aiEmbeddingDbList.value.find(item => item.id === mId)
  return aiEmbeddingDb ? aiEmbeddingDb.name : ''
}

function getRankModelName(mId) {
  const rankModel = rankModelList.value.find(item => item.id === mId)
  return rankModel ? rankModel.name : ''
}

function getReRankModelName(mId) {
  const reRankModel = reRankModelList.value.find(item => item.id === mId)
  return reRankModel ? reRankModel.name : ''
}


getList();
getRankModelList()
getReRankModelList()
getAiEmbeddingBb()
getTextSplitterTypeDataList()
</script>
